package com.zb.kc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.kc.client.VodClient;
import com.zb.kc.commonutils.ResultCode;
import com.zb.kc.entity.EduChapter;
import com.zb.kc.entity.EduCourse;
import com.zb.kc.dao.EduCourseDao;
import com.zb.kc.entity.EduCourseDescription;
import com.zb.kc.entity.EduVideo;
import com.zb.kc.entity.vo.CourseInfoVo;
import com.zb.kc.entity.vo.CoursePublishVo;
import com.zb.kc.entity.vo.CourseQueryVo;
import com.zb.kc.entity.vo.CourseWebVo;
import com.zb.kc.service.IEduChapterService;
import com.zb.kc.service.IEduCourseDescriptionService;
import com.zb.kc.service.IEduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.kc.service.IEduVideoService;
import com.zb.kc.servicebase.exceptionhandler.KgcException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wanggen
 * @since 2020-04-10
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseDao, EduCourse> implements IEduCourseService {

    @Autowired
    private IEduCourseDescriptionService courseDescriptionService;

    @Autowired
    private IEduChapterService chapterService;

    @Autowired
    private IEduVideoService videoService;

    @Autowired
    private EduCourseDao courseDao;

    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        // 向课程表中添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int insert = baseMapper.insert(eduCourse);
        // 判断是否添加成功，不成功直接抛出异常
        if (insert <= 0) {
            throw new KgcException(50000, "添加课程基本信息失败");
        }
        // 获取课程的id
        String cid = eduCourse.getId();
        // 向课程简介中添加课程简介
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescription.setId(cid);
        courseDescriptionService.save(courseDescription);
        return cid;
    }

    @Override
    public CoursePublishVo getCoursePublishById(String courseId) {
        return courseDao.getCoursePublishById(courseId);
    }

    @Override
    public Page<CourseInfoVo> getPageCourseInfoVo(Page<CourseInfoVo> page, CourseInfoVo courseInfoVo) {
        return courseDao.getPageCourseInfoVo(page, courseInfoVo);
    }

    /**
     * 用来调用远程的阿里云删除视频
     */
    @Autowired
    private VodClient vodClient;

    /**
     * 删除课程所有相关信息
     *
     * @param courseId
     */
    @Override
    @Transactional
    public void deleteCourseCascade(String courseId) {
        // 先查询除课程对应的所有的小节获取到视频的id也就是阿里云的视频id
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper();
        queryWrapper.select("video_source_id").eq("course_id", courseId);
        List<String> videoIds = (List) videoService.listObjs(queryWrapper);
        // 删除课程对应的小节,阿里云视频
        vodClient.deleteBathch(videoIds);
        // 删除课程
        int result = baseMapper.deleteById(courseId);
        if (!(result > 0)) {
            throw new KgcException(ResultCode.CANNOT_DELETE_COURSE);
        }
        // 删除课程描述
        courseDescriptionService.removeById(courseId);
        // 删除课程对应的章节们
        chapterService.remove(new QueryWrapper<EduChapter>().eq("course_id", courseId));
        videoService.remove(new QueryWrapper<EduVideo>().eq("course_id", courseId));
    }

    /**
     * 获取最热门的8门课程
     *
     * @return
     */
    @Cacheable(value = "educourse", key = "'getHotCourse'")
    @Override
    public List<EduCourse> getHotCourse() {
        // 查询前8条热门课程
        QueryWrapper<EduCourse> wrapperCourse = new QueryWrapper<>();
        wrapperCourse.orderByDesc("id").last("limit 8");
        return baseMapper.selectList(wrapperCourse);
    }

    /**
     * 根据讲师id查询课程
     *
     * @param id
     * @return
     */
    @Override
    public List<EduCourse> getCourseByTeacherId(String id) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("teacher_id", id);
        // 按照最新的更新时间排序
        wrapper.orderByDesc("gmt_modified");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public Page<EduCourse> pageListWeb(Page<EduCourse> page, CourseQueryVo courseQueryVo) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQueryVo.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQueryVo.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQueryVo.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQueryVo.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQueryVo.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQueryVo.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQueryVo.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }
        Page<EduCourse> eduCoursePage = baseMapper.selectPage(page, queryWrapper);
        return eduCoursePage;
    }

    @Override
    public CourseWebVo selectInfoWebById(String courseId) {
        this.updatePageViewCount(courseId);
        return baseMapper.selectInfoWebById(courseId);
    }

    @Override
    public void updatePageViewCount(String id) {
        EduCourse course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }
}
